import { message } from '@/components/XtxUI';
import type { CheckoutInfo, UserAddresse } from '@/types';
import { http } from '@/utils/request';
import { defineStore } from 'pinia';
import useStore from '@/store';
import router from '@/router';
import type { SubmitOrder, OrderDetail } from '@/types';
const useOrderStore = defineStore('Order', {
  // 状态
  state: () => ({
    // 订单信息
    checkoutInfo: {} as CheckoutInfo,
    // 收货地址
    currAddress: {} as UserAddresse,
    // 收货地址列表
    addressList: [{} as UserAddresse],
    // 临时收货地址
    tempAddress: {} as UserAddresse,
    // 订单信息
    orderPayInfo: {} as OrderDetail,
  }),
  // 计算
  getters: {},
  // 方法
  actions: {
    async createOrderPre() {
      const res = await http<CheckoutInfo>('GET', '/member/order/pre');
      // console.log('GET', '/member/order/pre', res.data.result);
      // 订单信息
      this.checkoutInfo = res.data.result;
      // 收货地址
      this.currAddress = res.data.result.userAddresses[0] || {};
      // 收货地址列表
      this.addressList = this.checkoutInfo.userAddresses;
    },
    // 点击确认收货地址
    confirmAddress() {
      // 确认收货地址
      this.currAddress = this.tempAddress;
    },
    // 点击提交订单按钮
    async createOrder(data: object) {
      // 在ts文件内调用其他store应该在函数内调用
      const { cart } = useStore();
      const res = await http<SubmitOrder>('POST', '/member/order', data);
      // 🚨替换成订单支付页(无需后退回来)
      router.replace(`/member/pay?orderId=${res.data.result.id}`);
      // 成功提醒用户
      message({ type: 'success', text: '下单成功，请及时支付~' });
      cart.getCartList();
    },
    // 获取我的订单详情
    async getOrderDetail(orderId: string) {
      const res = await http<OrderDetail>('GET', `/member/order/${orderId}`);
      // console.log('GET', `/member/order/${orderId}`, res.data.result);
      this.orderPayInfo = res.data.result;
    },
  },
});
export default useOrderStore;
